package
{
	import as3isolib.core.IIsoDisplayObject;
	import as3isolib.core.IsoDisplayObject;
	import as3isolib.display.scene.IsoScene;
	import as3isolib.geom.Pt;
	
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.geom.Vector3D;
	import flash.utils.getDefinitionByName;

	public class GMBuy implements IGameMode
	{
		private var m_gameObject:GameObject;
		private var m_isoScene:IsoScene;
		
		public function GMBuy(gameObject:GameObject, isoScene:IsoScene)
		{
			m_isoScene = isoScene;
			m_gameObject = gameObject;
			m_gameObject.initializeRendering();
			m_gameObject.isoDisplay.container.visible = false;
			
			m_isoScene.addChild(m_gameObject.isoDisplay);
		}
		
		
		public function onMouseDown(me:MouseEvent):void{
			
		}
		
		public function onMouseUp(me:MouseEvent):void{
			var currentPosition:Point = new Point(me.stageX, me.stageY);
			var isoPosition:Pt = Global.isoView.localToIso(currentPosition);
			var extrapolatedPosition:Vector3D = extrapolatePosition(isoPosition); 
			m_gameObject.model.location = extrapolatedPosition;
			
			Global.player.buy(m_gameObject);
			Global.inputManager.popGameMode();
			
			var classRef:Class = getDefinitionByName(m_gameObject.className) as Class;
			var config:GameObjectConfig = new GameObjectConfig();
			config.location = extrapolatedPosition;
			config.size = m_gameObject.model.size;
			var gameObject:GameObject = new classRef(new GameObjectModel(config));
			
			Global.inputManager.addGameMode(new GMBuy(gameObject, Global.isoScene));
		}
		
		public function onMouseMove(me:MouseEvent):void{
			var currentPosition:Point = new Point(me.stageX, me.stageY);
			var isoPosition:Pt = Global.isoView.localToIso(currentPosition);
			var extrapolatedPosition:Vector3D = extrapolatePosition(isoPosition);
			
			m_gameObject.isoDisplay.container.visible = true;
			Global.setLocation(m_gameObject.isoDisplay, extrapolatedPosition);
		}
		
		// for now this just snaps
		private function extrapolatePosition(pos:Pt):Vector3D{
			var sqSize:int = Constants.SQUARE_SIZE;
			var snappedX:Number = Math.round(pos.x/sqSize)*sqSize;
			var snappedY:Number = Math.round(pos.y/sqSize)*sqSize;
			var snappedZ:Number = Math.round(pos.z/sqSize)*sqSize;
			
			return new Vector3D(snappedX, snappedY, snappedZ);
		}		
	}
}